package com.example.recyclerviewdemo.tree

import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.constraintlayout.widget.ConstraintLayout
import com.blankj.utilcode.util.SizeUtils
import com.chad.library.adapter.base.entity.node.BaseNode
import com.chad.library.adapter.base.provider.BaseNodeProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.example.recyclerviewdemo.R

class RootNodeProvider : BaseNodeProvider() {

    override val itemViewType = 0

    interface TreeClick{
        fun click(label: String?, value: String?)
    }

    private lateinit var listener: TreeClick

    override val layoutId: Int
        get() = R.layout.item_tree_node0

    override fun convert(helper: BaseViewHolder, item: BaseNode) {
        if (item is TreeNodeData) {
            val treeImg = helper.getView<AppCompatImageView>(R.id.treeImg).apply {
                setOnClickListener {
                    getAdapter()?.expandOrCollapse(helper.adapterPosition)
                }
            }
            val treeNodeRootView = helper.getView<ConstraintLayout>(R.id.treeNodeRootView).apply {
                setOnClickListener {
                    if(::listener.isInitialized){
                        listener.click(item.label,item.value)
                    }
                }
            }

            val itemTreeNodeText = helper.getView<TextView>(R.id.itemTreeNodeText)

            treeNodeRootView.setPadding(item.level * SizeUtils.dp2px(16f), 0, 0, 0)

            //有无子节点
            if (item.children != null) {
                treeImg.visibility = View.VISIBLE
                if (item.isExpanded) { //展开状态
                    treeImg.setImageResource(R.drawable.arrow_up)
                } else {
                    treeImg.setImageResource(R.drawable.arrow_down)
                }
            } else {
                treeImg.visibility = View.GONE
            }
            itemTreeNodeText.text = item.label

        }
    }

    fun setListener(listener: TreeClick) {
        this.listener = listener
    }


}